{% extends "base.html" %}
{% block title %}{{title}} - checklists - {{tag|unquote}}{% endblock %}
{% block checklist %}
<!--CSS file (default YUI Sam Skin) -->
<link type="text/css" rel="stylesheet"
      href="http://yui.yahooapis.com/2.7.0/build/datatable/assets/skins/sam/datatable.css">
<link rel="stylesheet" type="text/css"
      href="http://yui.yahooapis.com/2.7.0/build/paginator/assets/skins/sam/paginator.css"/>
<!-- Dependencies -->
<script type="text/javascript" src="http://yui.yahooapis.com/2.7.0/build/element/element-min.js"></script>
<script type="text/javascript" src="http://yui.yahooapis.com/2.7.0/build/datasource/datasource-min.js"></script>
<!-- OPTIONAL: JSON Utility (for DataSource) -->
<script type="text/javascript" src="http://yui.yahooapis.com/2.7.0/build/json/json-min.js"></script>
<!-- OPTIONAL: Connection Manager (enables XHR for DataSource) -->
<script type="text/javascript" src="http://yui.yahooapis.com/2.7.0/build/connection/connection-min.js"></script>
<!-- OPTIONAL: Drag Drop (enables resizeable or reorderable columns) -->
<script type="text/javascript" src="http://yui.yahooapis.com/2.7.0/build/dragdrop/dragdrop-min.js"></script>
<!-- Source files -->
<script type="text/javascript" src="http://yui.yahooapis.com/2.7.0/build/datatable/datatable-min.js"></script>
<script type="text/javascript" src="http://yui.yahooapis.com/2.7.0/build/paginator/paginator-min.js"></script>
<script type="text/javascript" src="http://yui.yahooapis.com/2.7.0/build/button/button-min.js"></script>
<style type="text/css">
    .align_center {
        text-align: center !important;
    }
</style>
<script type="text/javascript">
    YAHOO.util.Event.addListener(window, "load", function() {
        YAHOO.checklist.TagedDynamicData = function() {
            var imageFormatter = function(elCell, oRecord, oColumn) {
                elCell.innerHTML = '<input type="image" src="/static/images/star.png"/>';
                elCell.style.cursor = 'pointer';
            };
            var detailLinkFormatter = function(elCell, oRecord, oColumn,oData) {
                elCell.innerHTML = '<a href="/list/' + oRecord.getData()['key'] + '"' + '>'+oRecord.getData()[oColumn.key]+'</a>';
            };
            // Column definitions
            var myColumnDefs = [ // sortable:true enables sorting
                {key:"check",resizeable:true,label:"Select Row",formatter:YAHOO.widget.DataTable.formatCheckbox,className:"align_center"},
                {key:"starred",resizeable:true,label:"Starred",formatter:imageFormatter,className:"align_center"},
                {key:"name", label:"Name", formatter:detailLinkFormatter,sortable:true},
                {key:"description", label:"Description",formatter:detailLinkFormatter, sortable:false},
                {key:"created_date", label:"Create Date", sortable:true,formatter:"date"},
                {key:"last_updated_date", label:"Update Date", sortable:true,formatter:"date"},
                {key:"key",resizeable:true,label:"Edit",formatter:function(elCell, oRecord, oColumn, oData){
                    elCell.innerHTML = "<a href='/edit/list/"+oData+"'>Edit</a>";
                }}
            ];

            // Custom parser
            var stringToDate = function(sData) {
                if (sData != null) {
                    var array = sData.split("-");
                    return new Date(array[1] + " " + array[2].slice(0, 2) + ", " + array[0]);
                }
            };

            var buildQueryString = function (state, dt) {
                return "?arg0="+encodeURIComponent("{{tag|unquote}}")+"&arg1=" + state.pagination.recordOffset +
                       "&arg2=" + state.pagination.rowsPerPage + '&time=' + new Date().getTime();
            };

            // DataSource instance
            var myDataSource = new YAHOO.util.DataSource("/json/getUserTagChecklists");
            myDataSource.responseType = YAHOO.util.DataSource.TYPE_JSON;
            myDataSource.responseSchema = {
                resultsList: "records",
                fields: [
                    {key:"name"},
                    {key:"description"},
                    {key:"created_date",parser:stringToDate},
                    {key:"last_updated_date",parser:stringToDate},
                    {key:"key"}
                ],
                metaFields: {
                    totalRecords: "totalRecords" // Access to value in the server response
                }
            };

            var myPaginator = new YAHOO.widget.Paginator({
                containers : ['paging_nav'],
                rowsPerPage : 10,
                rowsPerPageOptions : [10,20,30],
                template : "{PreviousPageLink} <strong>{CurrentPageReport}</strong> {NextPageLink} {LastPageLink} {RowsPerPageDropdown}"
            });

            // DataTable configuration
            var myConfigs = {
                initialRequest: "?arg0=\""+encodeURIComponent("{{tag|unquote}}")+"\"&arg1=0&arg2=10&time=" + new Date().getTime(),  //'startIndex=0&results=25'
                generateRequest: buildQueryString,
                dynamicData: true, // Enables dynamic server-driven data
                sortedBy : {key:"last_updated_date", dir:YAHOO.widget.DataTable.CLASS_ASC}, // Sets UI initial sort arrow
                paginator: myPaginator // Enables pagination
            };

            // DataTable instance
            var myDataTable = new YAHOO.widget.DataTable("checklists_container", myColumnDefs, myDataSource, myConfigs);
            // Update totalRecords on the fly with value from server
            myDataTable.handleDataReturnPayload = function(oRequest, oResponse, oPayload) {
                oPayload.totalRecords = oResponse.meta.totalRecords;
                return oPayload;
            };

            // Selects any cell that receives a checkbox click
            myDataTable.subscribe("checkboxClickEvent", function(oArgs) {
                var elCheckbox = oArgs.target;
                var elRow = this.getTrEl(elCheckbox);
                if (elCheckbox.checked) {
                    this.selectRow(elRow);
                } else {
                    this.unselectRow(elRow);
                }
            });

            // Move up/down the row that receives a up/down img click
            myDataTable.subscribe("buttonClickEvent", function(oArgs) {
                var elImage = oArgs.target;
                var elRow = this.getTrEl(elImage),
                        index = this.getTrIndex(elImage),
                        recordData = this.getRecord(elRow).getData();
                var mode = elImage.name;
                if (mode == "up") {
                    if (!YAHOO.lang.isNull(this.getPreviousTrEl(elImage))) {
                        this.deleteRow(index);
                        this.addRows([{name:recordData.name, type:recordData.type}], index - 1);
                    }
                } else if (mode == "down") {
                    if (!YAHOO.lang.isNull(this.getNextTrEl(elImage))) {
                        this.deleteRow(index);
                        this.addRows([{name:recordData.name, type:recordData.type}], index + 1);
                    }
                }
            });

            myDataTable.subscribe("cellClickEvent", myDataTable.onEventShowCellEditor);

            var newChecklist = function() {
                window.location.href = "/create/list";
            };
            var selectedChecklistIds = function(recordSet,selectedRows) {
                var checklist_keys  = "checklist_keys=";
                for (var x = 0, length=selectedRows.length; x < length; x++) {
                    var record =  recordSet.getRecord(selectedRows[x]);
                    checklist_keys += record.getData().key;
                    if(x < length-1){
                        checklist_keys+=",";
                    }
                }
                return checklist_keys;
            };
            var deleteChecklists = function() {
                var selected = myDataTable.getSelectedRows();
                var rset = myDataTable.getRecordSet();
                if (selected.length > 0) {
                    YAHOO.util.Connect.asyncRequest('POST', '/json/deleteChecklists',
                    {
                        success: function (o) {
                            if (o.responseText == 'true') {
                                for (var x = 0; x < selected.length; x++) {
                                    myDataTable.deleteRow(rset.getRecordIndex(rset.getRecord(selected[x])));
                                }
                            } else {
                                alert(o.responseText);
                            }
                        },
                        failure: function (o) {
                            alert(o.statusText);
                        },
                        scope:this
                    }, selectedChecklistIds(rset, selected)
                            );
                } else {
                    alert("Please select at least one Checklist to delete.");
                }
            };

            YAHOO.util.Event.addListener("addChecklist", "click", newChecklist);
            YAHOO.util.Event.addListener("deleteChecklist", "click", deleteChecklists);

            return {
                ds: myDataSource,
                dt: myDataTable
            };

        }();
    });
</script>
<div>
    Checklists tagged by <em>{{tag|unquote}}</em><br><br>
    <div style="padding-bottom:3px">
        <button id="addChecklist">Create New Checklist</button>
        <button id="deleteChecklist">Delete</button>
    </div>
    <div id="checklists_container">
    </div>
    <div id="paging_nav"> </div>
</div>
<br>
{% endblock %}

